import datetime

from peewee import *

database = 'peewee'
host = '127.0.0.1'
user = 'root'
passwd = '123456'
port = 3306
db = MySQLDatabase(database, host=host, user=user, passwd=passwd, port=port, charset='utf8mb4')


class User(Model):
    # 如果没有设置主键，那么自动生成一个id的主键
    username = CharField(max_length=30, verbose_name="名字", null=True)
    age = CharField(default=18, max_length=20, verbose_name="年龄", null=True)

    # migrations,

    class Meta:  # 大写
        database = db


class Tweet(Model):
    message = TextField(null=True)
    created_date = DateTimeField(default=datetime.datetime.now, null=True)
    is_published = BooleanField(default=True, null=True)

    class Meta:
        database = db


if __name__ == '__main__':
    # 1. 生成表结构
    db.connect()
    db.create_tables([User, Tweet])

    # # 2. 添加
    # charlie = User.create(username='charlie')
    # huey = User.create(username='huey')
    # mickey = User.create(username='mickey')

    # # 3. 查询
    # # 1. get方法 - 1. 返回来的是直接的user对象 2. 这个方法如果查询不到会抛出异常
    # try:
    #     # charlie = User.get(User.username == "charlie")
    #     charlie = User.get_by_id("1")
    #     print(charlie.username)
    #     # 这个操作发起的sql请求是什么
    # except User.DoesNotExist as e:
    #     print("查询不到")

    # # 2. 查询所有
    # users = User.select()  # 1. 没有看到sql查询语句，用于组装sql 2. 对象是ModelSelect 我们对ModelSelect进行for循环和切片的时候才会发起请求
    # print(users.sql())
    # # print(type(users))
    # user1 = users[0]
    # user2 = users[1:2]
    # print(type(user1))
    # print(type(user2))

    # usernames = ["charlie", "huey", "mickey"]
    # users = User.select().where(User.username.in_(usernames))
    # for user in users:
    #     print(user.username)
    # for user in User.select():
    #     print(user.username)

    # # 使用update更新
    # print(User.update(username='test').where(User.id == "1").execute())
    #
    # # 删除数据
    # query = User.delete().where(User.id == "14").execute()
    # print(query)
